package cn.bone.base.jms2;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by MD-01 on 2016/9/12.
 */
public class QueueReceiver {
    private static final String BROKE_URL = "tcp://localhost:61616";
    private static String TARGET = "cn.bone.queue";

    public static void run() throws Exception{
        QueueConnection connection = null;
        QueueSession session = null;

        //创建连接工厂
        QueueConnectionFactory factory = new ActiveMQConnectionFactory(
                ActiveMQConnection.DEFAULT_USER,
                ActiveMQConnection.DEFAULT_PASSWORD,
                BROKE_URL);

        //通过工厂创建一个连接
        connection = factory.createQueueConnection();
        //启动连接
        connection.start();
        //创建一个session会话
        session = connection.createQueueSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
        //创建一个消息队列
        Queue queue = session.createQueue(TARGET);
        javax.jms.QueueReceiver receiver = session.createReceiver(queue);

        receiver.setMessageListener(new MessageListener() {

            public void onMessage(Message message) {
                if(message != null){
                    MapMessage map = (MapMessage)message;
                    try {
                        System.out.println(map.getLong("time")+"接收#"+map.getString("text"));
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread.sleep(1000*100);
        session.commit();
        session.close();
        connection.close();
    }

    public static void main(String[] args){
        try {
            run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
